package com.smcdd.cdb.dbo.cdb_dbo.service.presenter;

import android.app.Dialog;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.network.HttpObserver;
import com.smcdd.cdb.dbo.cdb_dbo.network.factory.RetrofitFactory;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.BaseResponseEntity;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.MainTenance;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Tain_v2;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IMaintain;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IMaintainTwo;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.MaintainTwoActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.adapter.TainAdapter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BasePresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.fragment.DetailFragment;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DateUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DialogUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.TainDialog;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 作者：Administrator on 2017/7/17 20:33
 * 邮箱：zhanghuaiha@gmail.com
 */

public class MaintainTwoPresenter extends BasePresenter<IMaintainTwo> {

    private String versionCode;
    private String id;
    private String udid;
    private RecyclerView rv;
    private SwipeRefreshLayout srl;
    private TextView tv;
    private LinearLayoutManager linearLayoutManager;
    private TainAdapter tainAdapter;
    private int type = 0;
    private int num = 1;
    private int total;

    private String date = "";
    private String status = "";
    private TainDialog listDialog;
    private ImageView bg;
    private Dialog dialog;
    private ViewPager viewpager;
    private List<Integer> mList;
    private int TOTAL_SIZE = 26;
    private final int PAGE_SIZE = 10;
    private int mCount = 0;
    private DetailPagerAdapter mAdapter;
    private List<Tain_v2> data;
    private TextView leftTime;
    private TextView rightTime;
    private int cc = 1;


    public MaintainTwoPresenter(BaseActivity context) {
        super(context);
    }

    public void loadContacts(){
        versionCode = ObtainVersion.getVersionName(mContext);
        id = App.SP.getString("id", "");
        udid = App.SP.getString("udid", "");
        viewpager = getView().getVP();
        tv = getView().getTV();
        bg = getView().getBg();
        leftTime = getView().getLeftTime();
        rightTime = getView().getRightTime();
        leftTime.setText(DateUtils.getNextDay(System.currentTimeMillis(),"MM/dd",1));
        rightTime.setText(DateUtils.getTotDay(System.currentTimeMillis(),"MM/dd",1));

        mList = new ArrayList<>();
        for (int i = 0; i < PAGE_SIZE; i++) {
            mCount++;
            mList.add(mCount);
        }




//        linearLayoutManager = new LinearLayoutManager(mContext);
//        rv.setLayoutManager(linearLayoutManager);
//        setAdapter();
//        srl.setColorSchemeResources(R.color.title_bg,R.color.blue);
//        //下拉刷新
//        srl.setOnRefreshListener(() -> {
//            num = 0;
//            loadNetWork(num+"",date,status);
//        });


//        //加载更多
//        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    int lastVisiblePosition = linearLayoutManager.findLastVisibleItemPosition();
//                    if (lastVisiblePosition >= linearLayoutManager.getItemCount() - 1) {
//                        if (total < 20) {
//                            return;
//                        } else {
//                            loadNetWork(num+"",date,status);
//                        }
//                        num++;
//                        }
//                    }
//                }
//            });
    }

    private void setAdapter() {
        if (tainAdapter == null) {
            tainAdapter = new TainAdapter(mContext);
        }
        rv.setAdapter(tainAdapter);
        tainAdapter.setItemClickListenter((dataBean, position,flag,i) -> {
            long l = 0;
            if (this.date!= null&&!this.date.equals("")) {
                long time_long = DateUtils.getTime_long(date);
                l = time_long - 86400000;
            }else {
                l = System.currentTimeMillis() - 86400000;
            }
            String time = DateUtils.getTime(l);
            loadDiaolog(time,dataBean.getCharging_info_ids());
        });
    }

    public void setType(int type){
        num = 0;
        this.type = type;
        loadNetWork(num+"",date,status);
    }


    //加载默认数据
    public void loadNetWork(String num,String date,String status){
        TSDialog();
        String time = System.currentTimeMillis() + "";
        this.status = status;
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",time);
        map.put("v",versionCode);
        map.put("i", NetWorkCodeInfo.MAINTENANCE_PAGE_V2);
        map.put("udid",udid);
        map.put("eid",id);
        map.put("page_size","1000");
        map.put("page_index","0");
        if (date!= null&&!date.equals("")) {
            map.put("date",date);
        }
        if (this.status!= null &&!this.status.equals("")) {
            map.put("status",this.status);
        }
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getTain_v2(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<List<Tain_v2>>>() {
                    @Override
                    public void success(BaseResponseEntity<List<Tain_v2>> listBaseResponseEntity) {
//                        srl.setRefreshing(false);
                        Log.e("MaintainTwoPresenter","拿到数据");
                        if (listBaseResponseEntity.code == 200) {
                            data = listBaseResponseEntity.data;
                            if (mAdapter == null) {
                                mAdapter = new DetailPagerAdapter(mContext.getSupportFragmentManager());
                                viewpager.setAdapter(mAdapter);
                                viewpager.addOnPageChangeListener(new OnFragmentPageChangeListener());
                                viewpager.setCurrentItem(mList.size()*100);
                            }else {
                                mAdapter.notifyDataSetChanged();
                            }


//                            if (listBaseResponseEntity.data.size() > 0 && listBaseResponseEntity.data.get(0).getDate() != null) {
//                                tv_time.setText("当前日期："+listBaseResponseEntity.data.get(0).getDate());
//                            }else {
//                                tv_time.setText("当前日期："+date);
//                            }
//                            tv.setText(listBaseResponseEntity.total);
//                            if (num.equals("0")) {
//                                total = Integer.parseInt(listBaseResponseEntity.total);
//                                List<Tain_v2> data = listBaseResponseEntity.data;
//                                tainAdapter.addData(data);
//                                if (data.size() == 0) {
//                                    bg.setVisibility(View.VISIBLE);
//                                    rv.setVisibility(View.INVISIBLE);
//                                }else {
//                                    bg.setVisibility(View.INVISIBLE);
//                                    rv.setVisibility(View.VISIBLE);
//                                }
//                            }else {
//                                total = Integer.parseInt(listBaseResponseEntity.total);
//                                List<Tain_v2> data = listBaseResponseEntity.data;
//                                tainAdapter.addLastData(data);
//                            }
                        }
                        dialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
//                        srl.setRefreshing(false);
                        dialog.dismiss();
                        ToastUtil.showToast(mContext.getString(R.string.error_date));
                    }
                });
    }


    /**
     * 获取dialog数据
     * @param date
     * @param charging_info_ids
     */
    public void loadDiaolog(String date,String charging_info_ids){
        String time = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",time);
        map.put("v",versionCode);
        map.put("i", NetWorkCodeInfo.MAINTENANCE_CHARGING);
        map.put("udid",udid);
        map.put("eid",id);
        map.put("date",date);
        map.put("charging_info_ids",charging_info_ids);
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getmaintenance(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<List<MainTenance>>>() {
                    @Override
                    public void success(BaseResponseEntity<List<MainTenance>> mainTenanceBaseResponseEntity) {
                        if (mainTenanceBaseResponseEntity.code == 200) {
                            List<MainTenance> data = mainTenanceBaseResponseEntity.data;
                            Dialog(data);
                        }
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        ToastUtil.showToast(mContext.getString(R.string.error_date));
                    }
                });
    }

    public void Dialog( List<MainTenance> data) {
        listDialog = new TainDialog(mContext,data,"2");
        listDialog.show();
    }

    public void TSDialog(){
        dialog = DialogUtils.uploadDialog(mContext, mContext.getString(R.string.upload), true);
    }

    public void visible2gone(boolean flag){
        tainAdapter.visible2gone(flag);
    }

    private class DetailPagerAdapter extends FragmentStatePagerAdapter {

        public DetailPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Observable.timer(2, TimeUnit.SECONDS).subscribe(aLong -> {

            });
            Log.e("MaintainTwoPresenter","返回数据");
            return DetailFragment.newInstance(data);
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }
    }

    private class OnFragmentPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float offsetPerc,
                                   int offsetPixel) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageSelected(int position) {
            if (cc != 1) {
                int a = 1001 - position;
                leftTime.setText(DateUtils.getNextDay(System.currentTimeMillis(),"MM/dd",a));
                long time_long = DateUtils.getTime_long(DateUtils.getNextDay(System.currentTimeMillis(), "yyyy-MM-dd", a));
                rightTime.setText(DateUtils.getTotDay(time_long,"MM/dd",2));
                loadNetWork("0",DateUtils.getTotDay(time_long,"yyyy-MM-dd",1),"");
            }
            cc++;
        }
    }
}
